/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */
package com.intelligent.ispc.common.test.log;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * For testing the logback output, save log appender in a list.
 * using addToLogger() to add the logger which needs to be listen before test.
 *
 * Created by Peter.Li on 2015/10/9.
 */
public class LogbackListAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

	private final List<ILoggingEvent> logs = Lists.newArrayList();

	public LogbackListAppender() {
		start();
	}

	@Override
	protected void append(ILoggingEvent e) {
		logs.add(e);
	}

	public ILoggingEvent getFirstLog() {
		if (logs.isEmpty()) {
			return null;
		}
		return logs.get(0);
	}

	public String getFirstMessage() {
		if (logs.isEmpty()) {
			return null;
		}
		return getFirstLog().getFormattedMessage();
	}

	public ILoggingEvent getLastLog() {
		if (logs.isEmpty()) {
			return null;
		}
		return Iterables.getLast(logs);
	}

	public String getLastMessage() {
		if (logs.isEmpty()) {
			return null;
		}
		return getLastLog().getFormattedMessage();
	}

	public List<ILoggingEvent> getAllLogs() {
		return logs;
	}

	public int getLogsCount() {
		return logs.size();
	}

	public boolean isEmpty() {
		return logs.isEmpty();
	}

	public void clearLogs() {
		logs.clear();
	}

	public void addToLogger(String loggerName) {
		Logger logger = (Logger) LoggerFactory.getLogger(loggerName);
		logger.addAppender(this);
	}

	public void addToLogger(Class<?> loggerClass) {
		Logger logger = (Logger) LoggerFactory.getLogger(loggerClass);
		logger.addAppender(this);
	}

	public void addToRootLogger() {
		Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
		logger.addAppender(this);
	}

	public void removeFromLogger(String loggerName) {
		Logger logger = (Logger) LoggerFactory.getLogger(loggerName);
		logger.detachAppender(this);
	}

	public void removeFromLogger(Class<?> loggerClass) {
		Logger logger = (Logger) LoggerFactory.getLogger(loggerClass);
		logger.detachAppender(this);
	}

	public void removeFromRootLogger() {
		Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
		logger.detachAppender(this);
	}

}
